$(document).ready(function(){
    $("#yes1").css("color" , "lightgray");
	  
$("#yes1").click(function()
  {
    $("#yes1").css("color" , "white");
    $("#no1").css("color" , "lightgray");
  });
  $("#no1").click(function(){
    $("#no1").css("color" , "white");
    $("#yes1").css("color" , "lightgray");
  });
});

$(document).ready(function(){
    $("#ahyes1").css("color" , "lightgray");
    $("timeofvisit").val("0");
	  
$("#ahyes1").click(function()
  {
    $("#ahyes1").css("color" , "white");
    $("#ahno1").css("color" , "lightgray");
    $("timeofvisit").val("1");
  });
  $("#ahno1").click(function(){
    $("#ahno1").css("color" , "white");
    $("#ahyes1").css("color" , "lightgray");
    $("timeofvisit").val("0");
  });
});


var flag = 0;
$(function(){
	window.setTimeout(loadData,1000);
});

function loadData()
{
  if(flag == 0)
  {
    flag = 1;
    getFieldSelection('rpp','visits',null,changeAll);
	
  }
}

function changeAll()
{
loadEndOfLife(loadSelectedEndOfLifeData);
loadCoca('child',loadSelectedCocaData);
loadProcedures('procedure',loadSelectedProcedureData);
loadMatNew('maternity',loadSelectedMaternityData);
loadAdult('general',loadSelectedAdultData);
loadElderly(loadSelectedElderlyData);
changeTracking(changeDemographics);
loadNotes(changeDiagnosis);
//changeDiagnosis();
if(isNull(getParameterByName('id')))
{
 loadtracked();
}
}

function loadtracked()
{
$('#service').attr("value", Session.get("service"));
$('#location').attr("value", Session.get("location"));
$('#supervising').attr("value", Session.get("supervising"));
if(Session.get("afterhours") == 1)
$('input:radio[name=afterhours]')[0].checked = true;
$("#afterhours").checkboxradio();
changeTracking();
}
function loadSelectedAdultData()
{
	if(isNull(getParameterByName('id')) == false)
	{	var id1 = getParameterByName('id');
		getResultSet("rpp","get_selected_adult","id=" +id1 ,function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
			$('#'+catNoSpaces+' option[value='+row.adult_key+']').attr('selected',true);
			$('#'+catNoSpaces).selectmenu('refresh');
		  });
		}
	});
}
}
function loadSelectedCocaData()
{
	if(isNull(getParameterByName('id')) == false)
	{	var id1 = getParameterByName('id');
		getResultSet("rpp","get_selected_coca","id=" +id1 ,function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
			$('#'+catNoSpaces+' option[value='+row.coca_key+']').attr('selected',true);
			$('#'+catNoSpaces).selectmenu('refresh');
		  });
		}
	});
}
}
function loadSelectedProcedureData()
{
	if(isNull(getParameterByName('id')) == false)
	{	var id1 = getParameterByName('id');
		getResultSet("rpp","get_selected_procedure","id=" +id1 ,function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
			$('#'+catNoSpaces+' option[value='+row.procedure_key+']').attr('selected',true);
			$('#'+catNoSpaces).selectmenu('refresh');
		  });
		}
	});
}
}

function loadSelectedElderlyData()
{
	if(isNull(getParameterByName('id')) == false)
	{	var id1 = getParameterByName('id');
		getResultSet("rpp","get_selected_elderly","id=" +id1 ,function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
		   $('#elderly' + row.elderly_key).attr('checked',true).checkboxradio("refresh");
		  });
		}
	});
}
changeDiagnosis();
}

function loadSelectedEndOfLifeData()
{
	if(isNull(getParameterByName('id')) == false)
	{	var id1 = getParameterByName('id');
		getResultSet("rpp","get_selected_end_of_life","id=" +id1 ,function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
		   $('#end_of_life' + row.id).attr('checked',true).checkboxradio("refresh");
		  });
		}
	});
}
}

function loadSelectedMaternityData()
{
	if(isNull(getParameterByName('id')) == false)
	{	var id1 = getParameterByName('id');
		getResultSet("rpp","get_selected_maternity","id=" +id1 ,function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
			$('#'+catNoSpaces+' option[value='+row.maternity_key+']').attr('selected',true);
			$('#'+catNoSpaces).selectmenu('refresh');
		  });
		}
	});
}
}
function loadNotes(callback)
{
var text = "";
text = $("#notes").val();
if (text.indexOf('Reading') !== -1)
	$("#Reading").attr('checked',true).checkboxradio('refresh');
text = $("#notes").val();	
if (text.indexOf('More Cases') !== -1)
	$("#MoreCases").attr('checked',true).checkboxradio('refresh');
callback();
}
function loadProcedures(tab,callback)
{
if($('#'+tab+'_select').children().length <=1)
{
	getResultSet('rpp','get_procedures','',function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, ''); // get category with no special chars
			var catSelect=$('#'+catNoSpaces);
			if(catSelect.length <=0)
			{
				var begin = "<select data-theme='c' id='" + catNoSpaces + "' name='Rpp_procedure'>"
				$('#'+tab+'_select').append(begin + "</select>");
			}
			catSelect=$('#'+catNoSpaces);
			if (row.label == " No Procedure ")
			{
			catSelect.append("<option value='" + row.id + "'>" +row.category+" : "+ row.label + "</option>");
		   }
		   else
		   {
		   catSelect.append("<option value='" + row.id + "'> "+ row.label + "</option>");
		   }
		   }); 
		   $('select').live('change',function(e,val){
				$(this).parent().css('color','#000');
		   });
		}
		$('#'+tab+'_select').trigger("create");  
		$('#'+tab+'_select .ui-select').children().css('color','#AAA');
		callback();
	});         
}
}


function loadEndOfLife(callback)
{
	getResultSet('rpp','getEndOfLife','',function(data){
		if(isJSONString(data))
		{
			var end_of_life= $('#end_of_life');
			end_of_life.children().remove();
			$('#end_of_life').html('');
			var json = JSON.parse(data);
			$(json).each(function(i,row){
				end_of_life.append("<input type='checkbox' data-theme='c' name='end_of_life' id='end_of_life"+row.id+"' value='" + row.id + "' />");
			    end_of_life.append("<label for='end_of_life" + row.id+"'>"+row.label+"</label>");
			});
			end_of_life.trigger('create');
			callback();
		}
	});
}



function loadElderly(callback)
{
	getResultSet('rpp','get_elderly','',function(data){
		if(isJSONString(data))
		{
			var elderly= $('#elderly');
			elderly.children().remove();
			$('#elderly').html('');
			var json = JSON.parse(data);
			$(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
			var catDiv=$('#'+catNoSpaces);
			if(catDiv.length <=0)
			{
				elderly.append("<h2 data-theme='c'>"+ row.category+"</h2>");
				elderly.append("<div id='"+catNoSpaces+"'></div>");
			}
			catDiv=$('#'+catNoSpaces);
			catDiv.append("<input type='checkbox' data-theme='c' name='elderly' id='elderly"+row.id+"' value='" + row.id + "' />");
			catDiv.append("<label for='elderly" + row.id+"'>"+row.label+"</label>");
			});
			elderly.trigger('create');
			
		}
		callback();
	});
}


function changeDiagnosis()
{
	var text1 = "";
	var id1 = "";
	$('#assessment_selects').html('');
		
		$('#child select option:selected').each(function(i,select)
		{
			if($(this).text().indexOf('No Diagnosis')<0)
			{
				text1 = text1 + ($(this).text() + "<BR>");
			}
		});
		if(text1 != "")
		{
			$('#assessment_selects').append('<B> Care of Children</B><BR>');
			$('#assessment_selects').append(text1);
		}
		text1 = "";
		
		$('#general select option:selected').each(function(i,select)
		{
			if($(this).text().indexOf('No Diagnosis')<0)
			{
				text1 = text1 + ($(this).text() + "<BR>");
			}
		});
		if(text1 != "")
		{
			$('#assessment_selects').append('<B> Care of Adults</B><BR>');
			$('#assessment_selects').append(text1);
		}
		text1 = "";
		
		$('#elderly input[type=checkbox]').each(function()
		{
			if(this.checked)
			{
				id1 = $(this).attr("name");
				text1 = text1 + ($(this).next('label').text() + "<BR>");
			}
		});
		if(text1 != "")
		{
			$('#assessment_selects').append('<B> Care of Elderly</B><BR>');
			$('#assessment_selects').append(text1);
		}
		text1 = "";
		
		$('#maternity select option:selected').each(function(i,select)
		{
			if($(this).text().indexOf('No Diagnosis')<0)
			{
				text1 = text1 + ($(this).text() + "<BR>");
			}
		});
		if(text1 != "")
		{
			$('#assessment_selects').append('<B> Maternity and New Born</B><BR>');
			$('#assessment_selects').append(text1);
		}
		text1 = "";
		
		
		
		$('#end_of_life input[type=checkbox]').each(function()
		{
			if(this.checked)
			{
				id1 = $(this).attr("name");
				text1 = text1 + ($(this).next('label').text() + "<BR>");
			}
		});
		if(text1 != "")
		{
			$('#assessment_selects').append('<B> End of Life</B><BR>');
			$('#assessment_selects').append(text1);
		}
		text1 = "";
		

		$('#procedure select option:selected').each(function(i,select)
		{
			if($(this).text().indexOf('No Procedure')<0)
			{
				text1 = text1 + ($(this).text() + "<BR>");
			}
		});
		if(text1 != "")
		{
			$('#assessment_selects').append('<B> Procedure</B><BR>');
			$('#assessment_selects').append(text1);
		}
		text1 = "";

		

		
		
}
function changeTracking(callback)
{
	var text1 = "";
        $('#tracking_selects').empty();
        text1 = text1 + ($('#tracking_page input#date').val()) +": ";
        $('#tracking_page select option:selected').each(function(i,select)
        {
		if($(this).text().indexOf('Not Specified')<0)
                {
                        text1 = text1 + ($(this).text()) +", ";
                }
		
        });
	$('#tracking_page input:checked').each(function(i,select)
        {
        if($("label[for='"+$(this).attr("id")+"']").text() == "Yes")
	  	text1 = text1 + "After Hours"
	  else if(($("label[for='"+$(this).attr("id")+"']").text() == "No"))
	  	text1 = text1.substring(0, text1.length - 2);
	});	
	$('#tracking_selects').append(text1);
	changeDemographics();
	
}
function changeDemographics()
{
	var text1 = "";
        $('#demographics_selects').empty();
        $('#demographics_page select option:selected').each(function(i,select)
        {
                if($(this).text().indexOf('Not Specified')<0)
                {
                        text1 = text1 + ($(this).text()) +", ";
                }
        });
	var text2 = "";
	$('#demographics_page input:checked').each(function(i,select)
        {
          if($("label[for='"+$(this).attr("id")+"']").text() == "Yes")
	  	text1 = text1 + "Seen Before, "
	  else if(($("label[for='"+$(this).attr("id")+"']").text() == "No"))
	  	text1 = text1;//.substring(0, text1.length - 2);
	  else	
	  	text2 = text2 + $(this).attr("name").substring(3,$(this).attr("name").length) +", ";
        });
	text2 = text2.substring(0, text2.length - 2);
	if(text1 != "")
	{
	$('#demographics_selects').append(text1);
	}
	$('#demographics_selects').append(text2);
	defaultDemographics();
	
}
//$("#domain").live("change" , function() {
//$('#my-collaspible').bind('expand', function () {



        
function checkNotes()
{
	var note1 = $('input[name="Option2"]:checked').val();
	var note2 = $('input[name="Option1"]:checked').val();
	if(isNull(note1))
		note1="";
	if(isNull(note2))
		note2="";
	$('#notes').val(note1 +" "+note2);
} 
function submit(){ alert("New Visit Submitted Successfully!");}


function show_me(me,label)
{
	$('#general').hide();
	$('#child').hide();
	$('#elderly').hide();
	$('#procedure').hide();
	$('#end_of_life').hide();
	$('#maternity').hide();
	$('#' + me).show();
	$('[id$=assessment_header]').text(label);
	
}
function loadAdult(tab,callback)
{
if($('#'+tab+'_select').children().length <=1)
{
	getResultSet('rpp','get_adult','',function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, ''); // get category with no special chars
			var catSelect=$('#'+catNoSpaces);
			if(catSelect.length <=0)
			{
				var begin = "<select data-theme='c' id='" + catNoSpaces + "' name='adult'>"
				$('#'+tab+'_select').append(begin + "</select>");
			}
			catSelect=$('#'+catNoSpaces);
			if (row.label=="No Diagnosis")
			{
			catSelect.append("<option value='" + row.id + "'>" +row.category+" : "+ row.label + "</option>");
		   }
		   else if (row.label!="No Diagnosis")
		   {
		   catSelect.append("<option value='" + row.id + "'> "+ row.label + "</option>");
		   }
		
		    }); 
		   $('select').live('change',function(e,val){
				$(this).parent().css('color','#000');
		   });
		}
		$('#'+tab+'_select').trigger("create");  
		$('#'+tab+'_select .ui-select').children().css('color','#AAA');
		callback();
	});         
	 
}
}

function loadCoca(tab,callback)
{
if($('#'+tab+'_select').children().length <=1)
{
	getResultSet('rpp','get_coca','',function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, ''); // get category with no special chars
			var catSelect=$('#'+catNoSpaces);
			if(catSelect.length <=0)
			{
				var begin = "<select data-theme='c' id='" + catNoSpaces + "' name='coca'>"
				$('#'+tab+'_select').append(begin + "</select>");
			}
			catSelect=$('#'+catNoSpaces);
			if (row.label==" No Diagnosis ")
			{
			catSelect.append("<option value='" + row.id + "'>" +row.category+" : "+ row.label + "</option>");
		   }
		   else
		   {
		   catSelect.append("<option value='" + row.id + "'> "+ row.label + "</option>");
		   }
		   }); 
		   $('select').live('change',function(e,val){
				$(this).parent().css('color','#000');
		   });
		}
		$('#'+tab+'_select').trigger("create");  
		$('#'+tab+'_select .ui-select').children().css('color','#AAA');
		callback();
	});         
	 
}
}


function loadMatNew(tab,callback)
{
if($('#'+tab+'_select').children().length <=1)
{
	getResultSet('rpp','get_mat_new','',function(data){
		if(isJSONString(data))
		{
		  json = JSON.parse(data);
		  $(json).each(function(i,row){
			var catNoSpaces = row.category.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, ''); // get category with no special chars
			var catSelect=$('#'+catNoSpaces);
			if(catSelect.length <=0)
			{
				var begin = "<select data-theme='c' id='" + catNoSpaces + "' name='maternity'>"
				$('#'+tab+'_select').append(begin + "</select>");
			}
			catSelect=$('#'+catNoSpaces);
             if (row.label==" No Diagnosis ")
			{
			catSelect.append("<option value='" + row.id + "'>" +row.category+" : "+ row.label + "</option>");
		   }
		   else
		   {
		   catSelect.append("<option value='" + row.id + "'> "+ row.label + "</option>");
		   }		  
		   }); 
		   $('select').live('change',function(e,val){
				$(this).parent().css('color','#000');
		   });
		}
		$('#'+tab+'_select').trigger("create");  
		$('#'+tab+'_select .ui-select').children().css('color','#AAA');
		callback();
	});         
	 
}
}

function putVisitFact()
{
	Session.set("service",$('#service').val());
	Session.set("location",$('#location').val());
	Session.set("supervising",$('#supervising').val());
	Session.set("afterhours",$('input[name=afterhours]:checked').val());
	$.ajaxSetup({async:false});
	var subject = $('#age option:selected').text() + ", " + $('#gender option:selected').text();
	$('<input />').attr('type', 'hidden')
            .attr('name', 'subject')
            .attr('id', 'subject')
            .attr('value', subject)
            .appendTo('form');
			
	var currentTime = new Date();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
	var ampm = hours >= 12 ? 'PM' : 'AM';
	hours = hours % 12;
	hours = hours ? hours : 12; // the hour '0' should be '12'
	minutes = minutes < 10 ? '0'+minutes : minutes;
	var strTime = hours + ':' + minutes + ' ' + ampm;
	$('<input />').attr('type', 'hidden')
            .attr('name', 'time')
            .attr('id', 'time')
            .attr('value', strTime)
            .appendTo('form');
			
	putFact('rpp','notes','');
	$("input[name='factTable']").remove();
	putFact('rpp','visits','Visits.html');
	
	$.ajaxSetup({async:true});
}

function callback(){ // Close list view if a child member has been clicked
	$('ul[data-role="listview"]').children().click(function(e){
		$('#domain').trigger('collapse');
	});
}
$(function() {// make sides of dialogs transparent (must be coupled with form.css)
	/*$('div[data-role="dialog"]').live('pagebeforeshow', function(e, ui) {
		ui.prevPage.addClass("ui-dialog-background ");
	});
	
	$('div[data-role="dialog"]').live('pagehide', function(e, ui) {
		$(".ui-dialog-background ").removeClass("ui-dialog-background ");
	});*/
});
 
$(function(){ // Hide delete button if this is an new visit rather than existing
    if(isNull(getParameterByName('id')))
    {
        $('#deleteVisitButton').hide()
    }
});

function removeVisit()
{
    var result = confirm("Delete Selected Visit?");
    if(result == true)
    {
        executeQuery('rpp','deleteVisit', 'id='+getParameterByName('id'),
            function(data)
            {
                window.location="Visits.html";
            }
        );
    }
}

function defaultDemographics() {

// class="ui-btn-active ui-state-persist"
  if($('#age').val() <= 5)
  	show_me('child','Care of Children');
  else if($('#age').val() >5 && $('#age').val() <=8)	
  	show_me('general','Care of Adult');
  else
  	show_me('elderly','Care of Elderly');
}